package com.projectsquirrel;

import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class Confirmation extends Activity  {
	private static final int PREFERENCES_GROUP_ID = 11;
	private static final int PAGE_2 = 12;
	private static final int PAGE_3 = 13;
	private static final int PAGE_4 = 14;
	private static final int PAGE_5 = 15;
	private static final int PAGE_6 = 16;
	private static final int PAGE_7 = 17;
	private LocationManager myManager;
	private String TAG = "Project_2_Group_6";
	private Observation newObs;
	private AlertDialog.Builder builder;
	AlertDialog gpsAlert;    
	private LocListener Location_Listener;
    private Button submitButton;
    private TextView completitionStatus;
    private Context context;
    private EditText ConfirmZip;
    private int beforeL;
    private SharedPreferences pref;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.observationformhd);//layout 1.5
	    ImageButton infoIconButton = (ImageButton) findViewById(R.id.infoScreenIcon);
	    ImageButton settingsIconButton = (ImageButton) findViewById(R.id.settingsScreenIcon);
	    context = getApplicationContext();
	    submitButton = (Button) findViewById(R.id.submitButton);
	    myManager = (LocationManager) getSystemService(LOCATION_SERVICE);
	    Location_Listener = LocListener.getInstance(myManager, context);
	    pref = getSharedPreferences("AppSettings",MODE_PRIVATE);
	    String email = pref.getString("userEmail", null);
	    newObs = Observation.getInstance(email);
	    builder = new AlertDialog.Builder(this);
		builder.setMessage(
				"We're Sorry, your phone is in Airplane Mode, this feature prevents sending information, if you wish to try again"
						+ " disable Airplane Mode and press \"Try Again\" if not you may submit at anytime in saved observations on the main menu.")
				.setCancelable(false)
				.setPositiveButton("Try Again",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// Action for 'Yes' Button
								if(Location_Listener.airplaneMode()){
									gpsAlert = builder.create();
									gpsAlert.show();
								}
								else{
									Toast.makeText(getApplicationContext(),"Observation Submitted!",Toast.LENGTH_LONG).show();
									
									Log.i(TAG, newObs.toString());
									Intent i = new Intent(Confirmation.this, mainMenu1.class);
									i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
							        startActivity(i);
								}
							}
						})
				.setNegativeButton("Okay", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// Action for 'NO' Button
						dialog.cancel();
						Intent i = new Intent(Confirmation.this, mainMenu1.class);
						i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				        startActivity(i);
					}
				});
		
		ConfirmZip = (EditText) findViewById(R.id.confirmZIP);
		beforeL = 0;
		ConfirmZip.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
				
				if(s.toString().length()>5){
					ConfirmZip.setText(ConfirmZip .getText().toString().substring(0, beforeL));
					
				}
					
			}
		    public void beforeTextChanged(CharSequence s, int start, int count,
		            int after) {
		        // TODO Auto-generated method stub
		    	beforeL = count;
		    }
		 
		    public void onTextChanged(CharSequence s, int start, int before,
		            int count) {
		        // TODO Auto-generated method stub
		 
		    }
		});
		
		
		//.getText().toString()
	    newObs.setLatLong(Location_Listener.getLatitude(), Location_Listener.getLongitude());
		newObs.setZip(Location_Listener.getZipCode());
	    
	    
	    refreshViews();
	    
	    
		final EditText ZIP = (EditText) findViewById(R.id.confirmZIP);
		
		ZIP.setHint(newObs.getZIP());
	    completitionStatus = (TextView) findViewById(R.id.textView2);
	    completitionStatus.setText("Almost done! Just press Submit!");
	    
	    
	   


		
		
	  



	    infoIconButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(Confirmation.this, infoMenu.class);
		        startActivity(i);
			}	    	
	    });
	    
	    settingsIconButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(Confirmation.this, settingsMenu.class);
		        startActivity(i);
			}	    	

	    });

	    
	  
	    submitButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String zip =((EditText) findViewById(R.id.confirmZIP)).getText().toString();
				if(Location_Listener.airplaneMode()&& zip.length()==5){
					newObs.setZip(zip);
				}
				if(newObs.getZIP()==null && zip.length()==5){
			    	newObs.setZip(zip);
			    }
			    if(newObs.getZIP()!=null && newObs.getZIP().length()!=5 && zip.length()!=5){
					//Toast.makeText(context, newObs.getZIP().length(), 5000).show();
			    	//newObs.setZip(zip);
					Toast.makeText(context, "Please enter a proper ZipCode.", 5000).show();
			    }
			    else if(newObs.getZIP()==null && zip.length()!=5){
			    	Toast.makeText(context, "Please enter a proper ZipCode.", 5000).show();
			    }
			    else if(newObs.getZIP()!=null && zip.length()==5){
			    		//Toast.makeText(context, "ZipCode="+zip, 5000).show();
			    		
			    		newObs.setZip(zip);
				    	/*
						 * Please Note!
						 * This question only needs to be asked once and it will
						 * be entered into user Preferences, it is asking if 
						 * a user has submitted data for a different
						 * site before. If a user answers yes, this will
						 * become an auto-complete answer, if a user enters
						 * "NO" then it will re appear until a counter for the
						 * number times a user submits an obs
						 * while selecting "NO" on using them same site
						 * if the counter >= 2 this question will disappear.
						 * 
						 *   -Daniel
						 */				
						int diffSiteCount = 0;
						SharedPreferences.Editor editor = pref.edit();
						if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
							newObs.setUsingDifSite("YES");
						}
						else{
							//it must be false
							if(newObs.getUsingSameSite().equals("NO")){
								diffSiteCount = pref.getInt("DifSiteCounter", 0);								
								editor.putInt("DifSiteCounter", diffSiteCount+1);
								editor.commit();
								int temp = pref.getInt("DifSiteCounter", 0);
								if(temp>=2){
									//Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
									editor.putBoolean("SubmitDifSiteBefore", true);
									editor.commit();
								}
							}
							else{
								//yes, using the same site						
								int temp = pref.getInt("DifSiteCounter", 0);
								if(temp>=2){
									//Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
									editor.putBoolean("SubmitDifSiteBefore", true);
									editor.commit();
								}
							}
						}		   
				    	String fName = newObs.getName();
						try{
							OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fName+".obs", 0));
							out.write(newObs.toString());
							out.close();
						}
						catch(Throwable t) {
							Log.e("I/O Error", t.toString());
						}
						if(Location_Listener.airplaneMode()){
							gpsAlert = builder.create();
							gpsAlert.show();
						}
						else{
							Toast.makeText(getApplicationContext(),"Observation Submitted!",Toast.LENGTH_LONG).show();
							Log.i(TAG, newObs.toString());
							Location_Listener.stopListening();
							Intent i = new Intent(Confirmation.this, mainMenu1.class);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					        startActivity(i);
					        newObs = null;
					        Observation.resetInstance();
					        System.gc();
						}
						
			    	}
			    else {
			    	//Toast.makeText(context, "ZipCode="+zip, 5000).show();
		    		newObs.setZip(Location_Listener.getZipCode());
			    	/*
					 * Please Note!
					 * This question only needs to be asked once and it will
					 * be entered into user Preferences, it is asking if 
					 * a user has submitted data for a different
					 * site before. If a user answers yes, this will
					 * become an auto-complete answer, if a user enters
					 * "NO" then it will re appear until a counter for the
					 * number times a user submits an obs
					 * while selecting "NO" on using them same site
					 * if the counter >= 2 this question will disappear.
					 * 
					 *   -Daniel
					 */				
					int diffSiteCount = 0;
					SharedPreferences.Editor editor = pref.edit();
					if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
						newObs.setUsingDifSite("YES");
					}
					else{
						//it must be false
						if(newObs.getUsingSameSite().equals("NO")){
							diffSiteCount = pref.getInt("DifSiteCounter", 0);								
							editor.putInt("DifSiteCounter", diffSiteCount+1);
							editor.commit();
							int temp = pref.getInt("DifSiteCounter", 0);
							if(temp>=2){
								//Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
								editor.putBoolean("SubmitDifSiteBefore", true);
								editor.commit();
							}
						}
						else{
							//yes, using the same site						
							int temp = pref.getInt("DifSiteCounter", 0);
							if(temp>=2){
								//Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
								editor.putBoolean("SubmitDifSiteBefore", true);
								editor.commit();
							}
						}
					}		   
			    	String fName = newObs.getName();
					try{
						OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fName+".obs", 0));
						out.write(newObs.toString());
						out.close();
					}
					catch(Throwable t) {
						Log.e("I/O Error", t.toString());
					}
					if(Location_Listener.airplaneMode()){
						gpsAlert = builder.create();
						gpsAlert.show();
					}
					else{
						Toast.makeText(getApplicationContext(),"Observation Submitted!",Toast.LENGTH_LONG).show();
						Log.i(TAG, newObs.toString());
						Location_Listener.stopListening();
						Intent i = new Intent(Confirmation.this, mainMenu1.class);
						i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				        startActivity(i);
				        newObs = null;
				        Observation.resetInstance();
				        System.gc();
					}
			    }
				    	
			}

				
								
			
	    });

	 

	
     }
     	@Override
	protected void onStart(){
     	// for the dialog indicating the gps is disabled
		super.onStart();
	}
	@Override
	protected void onDestroy() {
		Location_Listener.stopListening();
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
		//stopListening();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		//startListening();
		super.onResume();
	}
	
	private void refreshViews()
	{
		((TextView) findViewById(R.id.confirmTime)).setText(newObs.getTime());
		((TextView) findViewById(R.id.confirmBird)).setText(newObs.getFeedFromBirdFeeder());
		((TextView) findViewById(R.id.confirmCone)).setText(newObs.getConTrees());
		((TextView) findViewById(R.id.confirmDate)).setText(newObs.getDate());
		((TextView) findViewById(R.id.confirmEmail)).setText(newObs.getEmail());
		if(newObs.getFeedFromComments().trim().length() != 0)
			((TextView) findViewById(R.id.confirmFeedComments)).setText(newObs.getFeedFromComments());
		((TextView) findViewById(R.id.confirmFruit)).setText(newObs.getFruitTrees());
		((TextView) findViewById(R.id.confirmGarbage)).setText(newObs.getFeedFromGarbage());
		((TextView) findViewById(R.id.confirmHandouts)).setText(newObs.getFeedFromHandouts());
		((TextView) findViewById(R.id.confirmLatitude)).setText("" + newObs.getLatitude());
		((TextView) findViewById(R.id.confirmLongitude)).setText(newObs.getLongitude() + "");
		((TextView) findViewById(R.id.confirmNumFox)).setText(newObs.getNumOfFoxSquirrels());
		((TextView) findViewById(R.id.confirmNumGray)).setText(newObs.getNumOfGraySquirrels());
		((TextView) findViewById(R.id.confirmNumSquirrelChange)).setText(newObs.getNumOfSqurChange());
		((TextView) findViewById(R.id.confirmNut)).setText(newObs.getNutTrees());
		((TextView) findViewById(R.id.confirmOtherFeed)).setText(newObs.getFeedFromOther());
		if(newObs.getOtherTreeComments().trim().length() != 0)
			((TextView) findViewById(R.id.confirmOtherTree)).setText(newObs.getOtherTreeComments());
		((TextView) findViewById(R.id.confirmPlants)).setText(newObs.getFeedFromTrees());
		((TextView) findViewById(R.id.confirmSeed)).setText(newObs.getSeedTrees());
		((TextView) findViewById(R.id.confirmSetting)).setText(newObs.getSetting());
		((TextView) findViewById(R.id.confirmTiny)).setText(newObs.getTinyTrees());
		((EditText) findViewById(R.id.confirmZIP)).setHint(newObs.getZIP());
		((TextView) findViewById(R.id.confirmCats)).setText(newObs.getNumOfSiteCats());
		((TextView) findViewById(R.id.confirmCoyotes)).setText(newObs.getNumOfSiteCoyotes());
		((TextView) findViewById(R.id.confirmDogs)).setText(newObs.getNumOfSiteDogs());
		if(newObs.getGeneralComments().trim().length() != 0)
			((TextView) findViewById(R.id.confirmGeneralComments)).setText(newObs.getGeneralComments());
		((TextView) findViewById(R.id.confirmHawks)).setText(newObs.getNumOfSiteHawks());
		((TextView) findViewById(R.id.confirmPGrain)).setText(newObs.getNumOfSitePGrain());
		((TextView) findViewById(R.id.confirmSameSite)).setText(newObs.getUsingSameSite());
		((TextView) findViewById(R.id.confirmDiffSite)).setText(newObs.getUsedDifferentSite());
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
	        
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
	super.onCreateOptionsMenu(menu);

	menu.add(PREFERENCES_GROUP_ID, PAGE_2, 0, "Date/Time")
	.setIcon(R.drawable.menuicondatetime);
	menu.add(PREFERENCES_GROUP_ID, PAGE_3, 0, "General")
	.setIcon(R.drawable.menuicongencom);
	menu.add(PREFERENCES_GROUP_ID, PAGE_4, 0, "Setting")
	.setIcon(R.drawable.menuiconsetting);
	menu.add(PREFERENCES_GROUP_ID, PAGE_5, 0, "Trees")
	.setIcon(R.drawable.menuicontree);
	menu.add(PREFERENCES_GROUP_ID, PAGE_6, 0, "Food")
	.setIcon(R.drawable.menuiconfood);
	menu.add(PREFERENCES_GROUP_ID, PAGE_7, 0, "Predators")
	.setIcon(R.drawable.menuiconpred);

	return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent i;
		switch (item.getItemId()) {
		case PAGE_2:
			i = new Intent(Confirmation.this, NewObservation2.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
	        break;
		case PAGE_3:
			i = new Intent(Confirmation.this, NewObservation3.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
	        break;
		case PAGE_4:
			i = new Intent(Confirmation.this, NewObservation4.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
 	        break;
		case PAGE_5:
			i = new Intent(Confirmation.this, NewObservation5.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
	        break;
	    case PAGE_6:
	    	i = new Intent(Confirmation.this, NewObservation6.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
	        break;
		case PAGE_7:
			i = new Intent(Confirmation.this, NewObservation7.class);
	        i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
	        startActivityForResult(i, 1);
	        break;
	    }
		return true;
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        refreshViews();
	}
	    
}

